Sample test 생성


In [42]:
import random 

alldata = []
all_words = "apple banana orange mango blueberry pizza cheese naruto".split()
for _ in range(5):
    fruit = {}
    for word in all_words: 
        n = random.randint(0,5) * 10
        if n != 0:
            fruit[word] = n
    # print fruit
    alldata.append(fruit)

alldata


Out[42]:
[{'apple': 50,
  'banana': 30,
  'orange': 40,
  'mango': 40,
  'blueberry': 30,
  'pizza': 40,
  'cheese': 10,
  'naruto': 20},
 {'banana': 20,
  'orange': 20,
  'blueberry': 40,
  'pizza': 30,
  'cheese': 30,
  'naruto': 10},
 {'apple': 50, 'orange': 30, 'blueberry': 40, 'cheese': 50, 'naruto': 40},
 {'banana': 20, 'orange': 20, 'mango': 50, 'cheese': 10, 'naruto': 50},
 {'banana': 30,
  'orange': 10,
  'mango': 40,
  'blueberry': 40,
  'cheese': 50,
  'naruto': 50}]

pandas 에 추가


In [43]:
import pandas as pd

In [44]:
df = pd.DataFrame()
df['all'] = alldata
df


Out[44]:
all
0 {'apple': 50, 'banana': 30, 'orange': 40, 'man...
1 {'banana': 20, 'orange': 20, 'blueberry': 40, ...
2 {'apple': 50, 'orange': 30, 'blueberry': 40, '...
3 {'banana': 20, 'orange': 20, 'mango': 50, 'che...
4 {'banana': 30, 'orange': 10, 'mango': 40, 'blu...

함수 정의


In [45]:
def getCount(item, **kwargs):
    column = kwargs['name']
    if column in item:
        return item[column]
    else:
        return 0

In [46]:
i = df.loc[0]['all']
i


Out[46]:
{'apple': 50,
 'banana': 30,
 'orange': 40,
 'mango': 40,
 'blueberry': 30,
 'pizza': 40,
 'cheese': 10,
 'naruto': 20}

In [47]:
getCount(i, name='apple')


Out[47]:
50

apply에 사용하기


In [48]:
df['all']


Out[48]:
0    {'apple': 50, 'banana': 30, 'orange': 40, 'man...
1    {'banana': 20, 'orange': 20, 'blueberry': 40, ...
2    {'apple': 50, 'orange': 30, 'blueberry': 40, '...
3    {'banana': 20, 'orange': 20, 'mango': 50, 'che...
4    {'banana': 30, 'orange': 10, 'mango': 40, 'blu...
Name: all, dtype: object

In [49]:
cols = ['apple', 'banana']
for col in cols:
    df[col] = df['all'].apply(getCount, name = col)

In [50]:
df


Out[50]:
all apple banana
0 {'apple': 50, 'banana': 30, 'orange': 40, 'man... 50 30
1 {'banana': 20, 'orange': 20, 'blueberry': 40, ... 0 20
2 {'apple': 50, 'orange': 30, 'blueberry': 40, '... 50 0
3 {'banana': 20, 'orange': 20, 'mango': 50, 'che... 0 20
4 {'banana': 30, 'orange': 10, 'mango': 40, 'blu... 0 30

In [ ]: